package org.tbstore.client;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

import java.util.zip.DataFormatException;
import java.util.zip.Inflater;

public class MessageReceivePacket extends DataInputStream {
    public MessageReceivePacket(InputStream i) {
        super(i);
    }

    public byte[] uncompressData(byte[] input, int uncompr_len)
            throws IOException, DataFormatException {
        Inflater              decompressor = new Inflater();
        ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompr_len);
        byte[]                buf = new byte[uncompr_len];

        decompressor.setInput(input);

        while (!decompressor.finished()) {
            int count = decompressor.inflate(buf);

            if (count <= 0) {
                break;
            }

            bos.write(buf, 0, count);
        }

        decompressor.end();

        return bos.toByteArray();
    }

    public int readCInt() throws IOException {
        int ch1 = in.read();
        int ch2 = in.read();
        int ch3 = in.read();
        int ch4 = in.read();

        if ((ch1 | ch2 | ch3 | ch4) < 0) {
            throw new EOFException();
        }

        return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
    }

    public int readCShort() throws IOException {
        int ch1 = in.read();
        int ch2 = in.read();

        if ((ch1 | ch2) < 0) {
            throw new EOFException();
        }

        return ((ch2 << 8) + (ch1 << 0));
    }

    public int readBytes(byte[] b) throws IOException {
        int len    = b.length;
        int nleft  = len;
        int offset = 0;
        int i      = 0;

        while (nleft > 0) {
            i = read(b, offset, nleft);

            if (i == -1) {
                break;
            }

            nleft -= i;
            offset += i;
        }

        return (len - nleft);
    }

    public Object getObject(int len, int uncompr_len)
            throws IOException, DataFormatException, ClassNotFoundException {
        if (len <= 4) {
            return null;
        }

        len -= 4;

        byte[] b = new byte[len];

        readBytes(b);

        if (uncompr_len > 0) {
            byte[] s = uncompressData(b, uncompr_len);

            if (s.length == uncompr_len) {
                b = s;
            }
        }

        ByteArrayInputStream byteIn = new ByteArrayInputStream(b);
        ObjectInputStream    objIs = new ObjectInputStream(byteIn);

        Object               object = objIs.readObject();

        objIs.close();

        return object;
    }
}
